//
//  RelationshipViewController.m
//  cliqset
//
//  Created by David Hinson on 3/16/09.
//  Copyright 2009 Cliqset, Inc.. All rights reserved.
//

#import "RelationshipViewController.h"
#import "cliqsetAppDelegate.h"
#import "Relationship.h"

@implementation RelationshipViewController

@synthesize myNavBar;
@synthesize mySegControl;
@synthesize myRelationshipsTable;
@synthesize navBarImage;
@synthesize hoverView;
@synthesize filter;

-(void)insertLogoArtIntoTitle {
	
	UIColor* myOrange			= [UIColor colorWithRed:255.0/255.0 green:155.0/255.0 blue:5.0/255.0 alpha:1.0];
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	UINavigationController* nc;
	
	for( UIViewController* vc in [myApp tabBarController].viewControllers ) {
		NSString* testString = (NSString*)vc.title;
		if ([testString isEqualToString:@"Relationships"]) {
			nc = (UINavigationController *)vc;
			nc.navigationBar.tintColor = myOrange;
			break;
		}
	}
}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 0) {
		
		cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
		
		// Do something refresh-ish
		NSLog(@"refreshRelationships");
		
		// Start showing the hover view...
		[myApp showRelationshipsHoverView:YES];
		
		// And then this should do the trick...
		[myApp.cliqset getRelationships];
	}
}

-(IBAction)refreshRelationships:(id)someObject {
	
    UIAlertView* myAlert = [[UIAlertView alloc] initWithTitle:@"cliqset" message:@"This may take several minutes.\r\n\nDo you wish to refresh Relationships?" delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:nil];
	
	[myAlert addButtonWithTitle:@"No"];
	
    [myAlert show];
    [myAlert release];    
}

// Setup the segmented control
-(void)setupSegmentedControl {
	UIColor* myOrange			= [UIColor colorWithRed:255.0/255.0 green:155.0/255.0 blue:5.0/255.0 alpha:1.0];
	
	[self.mySegControl setWidth:30.0 forSegmentAtIndex: 0];
	[self.mySegControl setWidth:60.0 forSegmentAtIndex: 1];
	[self.mySegControl setWidth:50.0 forSegmentAtIndex: 2];
	[self.mySegControl setWidth:84.0 forSegmentAtIndex: 3];
	[self.mySegControl setWidth:80.0 forSegmentAtIndex: 4];
	
	[self.mySegControl addTarget:self action:@selector(segmentTouched:) forControlEvents:UIControlEventValueChanged];
	
	self.mySegControl.tintColor = myOrange;
}

// Load filter
-(void)loadFilter {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	[self.filter removeAllObjects];
	
	NSMutableString * filterEntry;
	for (int x=0; x<[myApp.relationships count]; x++) {
		if ([self displayMe:x]) {
			filterEntry = (NSMutableString*)[@"" stringByAppendingFormat:@"%d", x];
			[self.filter addObject:filterEntry];
		}
	}
}

// reset segment control
-(void)resetSegment {
	self.mySegControl.selectedSegmentIndex = 0;
}

// Segmented control has been touched
-(IBAction)segmentTouched:(id)someObject {
	
	// NSLog(@"%d", self.mySegControl.selectedSegmentIndex);
	[self loadFilter];
	
	[self showHoverView:YES];
	[self.myRelationshipsTable reloadData];
	[self showHoverView:NO];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
    [super viewDidLoad];
	
	self.filter = [[NSMutableArray alloc] init];
	
	// Load filter
	[self loadFilter];
	
	hoverView.center = [self view].center;
	
	[[self view] addSubview:hoverView];
	[[self view] bringSubviewToFront:hoverView];
	
	[self insertLogoArtIntoTitle];
	[self setupSegmentedControl];
	
	UIBarButtonItem *addButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addRelationship:)] autorelease];
	self.navigationItem.rightBarButtonItem = addButton;
}

// Add relationship
-(void)addRelationship:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];

	NSLog(@"addRelationship");
	UIBarButtonItem *backBar = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleDone target:nil action:nil];
	self.navigationItem.backBarButtonItem = backBar;	
	[backBar release];
	
	// Clear all previous results
	[myApp.queryResults removeAllObjects];

	// And then show the query screen
	[myApp slideQueryUsersIn];
}

- (void)showHoverView:(BOOL)show
{
	// fade animate the view out of view by affecting its alpha
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.40];
    
	if (show)
	{
		hoverView.alpha = 0.85;
	}
	else
	{
		hoverView.alpha = 0.0;
	}
	
	[UIView commitAnimations];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

// Determine whether to display cell
-(BOOL)displayMe:(int)row {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	Relationship *deref = (Relationship *)[myApp.relationships objectAtIndex:row];
	NSMutableString* test = @"";
	
	switch(self.mySegControl.selectedSegmentIndex) {
		case 0:
			return true;
			break;
		case 1:
			for (int y=0; y<[deref.tags count]; y++) {
				if ([[deref.tags objectAtIndex:y] isKindOfClass:[Tag class]]) {
					Tag* tag = (Tag*)[deref.tags objectAtIndex:y];
					test = tag.tag;
				}
				else {
					test = (NSMutableString*)[deref.tags objectAtIndex:y];
				}
				if ([test isEqualToString:@"Friend"]) {
					return true;
				}
			}
			return false;
			break;
		case 2:
			for (int y=0; y<[deref.tags count]; y++) {
				if ([[deref.tags objectAtIndex:y] isKindOfClass:[Tag class]]) {
					Tag* tag = (Tag*)[deref.tags objectAtIndex:y];
					test = tag.tag;
				}
				else {
					test = (NSMutableString*)[deref.tags objectAtIndex:y];
				}
				if ([test isEqualToString:@"Family"]) {
					return true;
				}
			}
			return false;
			break;
		case 3:
			for (int y=0; y<[deref.tags count]; y++) {
				if ([[deref.tags objectAtIndex:y] isKindOfClass:[Tag class]]) {
					Tag* tag = (Tag*)[deref.tags objectAtIndex:y];
					test = tag.tag;
				}
				else {
					test = (NSMutableString*)[deref.tags objectAtIndex:y];
				}
				if ([test isEqualToString:@"Professional"]) {
					//	if ([test isEqualToString:@"Colleague"]) {
					return true;
				}
			}
			return false;
			break;
		case 4:
			for (int y=0; y<[deref.tags count]; y++) {
				if ([[deref.tags objectAtIndex:y] isKindOfClass:[Tag class]]) {
					Tag* tag = (Tag*)[deref.tags objectAtIndex:y];
					test = tag.tag;
				}
				else {
					test = (NSMutableString*)[deref.tags objectAtIndex:y];
				}
				if ([test isEqualToString:@"Classmate"]) {
					return true;
				}
			}
			return false;
			break;
		default:
			return false;
			break;
	}
}

#pragma mark ---- table handling ----

// Number of table sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 2;
}

// Return rows in table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	BOOL found = 0;
	
	switch (section) {
		case 0:
			for (int x=0; x<[myApp.notifications count]; x++) {
				UIView * view = (UIView*)[myApp.notifications objectAtIndex:x];
				if (view.tag == -2) {found=YES;}
				}
			if (found==YES) {return 1;} else {return 0;}
		case 1:
			if ([myApp.relationships count] == 0) {[self showHoverView:NO];}
	
			return [filter count];
			break;
		}
	
	return 0;
}

// Set Section Header Height
- (CGFloat)tableView:(UITableView *)aTableView heightForHeaderInSection:(NSInteger)section{
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	if (section == 0) {
		if ([myApp.notifications count] == 0) {
			return 0.0;
		} 		
		BOOL found = 0;
		for (int x=0; x<[myApp.notifications count]; x++) {
			UIView * view = (UIView*)[myApp.notifications objectAtIndex:x];
			if (view.tag == -2) {found=YES;}
			}
		if (found) {return 30;} else {return 0;}
	}
	else {
		if (([myApp.relationships count]) == 0 || ([myApp.notifications count] == 0)) {
			return 0.0;
			} 			
		if (([myApp.notifications count] == 1)) {
			UIView * view = (UIView*)[myApp.notifications objectAtIndex:0];
			if (view.tag == -1) {return 0.0;}
			}
		}
	
	return 30.0;
}

// Set row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	if (indexPath.row >= [myApp.relationships count]) {
		NSLog(@"Relationship Exception thrown");
		return 1.0;
		}
	
	switch (indexPath.section) {
		case 0:
			return 40.0;
			break;
		case 1:
			return 53.0;
			break;
		}
	
	return 53.0;
}

- (NSString *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
	
	UIView *headerView           = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 40.0)] retain];
	
    UIColor* myGray              = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];	
    UILabel* sectionTitle        = [[UILabel alloc] initWithFrame:CGRectMake(9.0, 5.0, 302.0, 30.0)];
	
    sectionTitle.textColor       = myGray;
    sectionTitle.textAlignment   = UITextAlignmentLeft;
	sectionTitle.backgroundColor = [UIColor clearColor];
    sectionTitle.font            = [UIFont boldSystemFontOfSize:16];
	headerView.backgroundColor   = [UIColor whiteColor];
	
    switch (section) {
        case 0:
			sectionTitle.text = @"Notifications";
			break;
		case 1:
			sectionTitle.text = @"Relationships";
            break;
        default:
			return nil;
            break;
    }
	
	[headerView addSubview:sectionTitle];	
	[sectionTitle release];
	
    return (NSString *)headerView;
}

// Draw cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
    
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
    [cell backgroundView].opaque=YES;
    [cell backgroundView].clearsContextBeforeDrawing;
   	[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
		
	UIColor* textColor = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];
	
	NSString * offset;
	Relationship *relationship;
	UIView * view;
	
	switch (indexPath.section) {
		case 0:
			
			for (int x=0; x<[myApp.notifications count]; x++) {
				view = (UIView *)[myApp.notifications objectAtIndex:x];
				if (view.tag == -2) {[cell addSubview:view];}
				}
			return cell;
			break;
			
		case 1:
			
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
			
			if (indexPath.row >= [myApp.relationships count]) {
				NSLog(@"Relationship Exception thrown");
				return cell;
			}
			
			// Dereference our contact
			offset       = [self.filter objectAtIndex:indexPath.row];
			relationship = (Relationship*)[myApp.relationships objectAtIndex:[offset intValue]]; 
			
			NSData* imageData         = relationship.target.avatarBlob;
			UIImage * graphic         = (UIImage*)[[UIImage alloc] initWithData:imageData];
	
			UIImageView *showImage = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, ((54-(40 * graphic.size.height / graphic.size.width))/2.0), 40.0, 40.0 * (graphic.size.height / graphic.size.width))];
			showImage.opaque              = NO;    
			showImage.image               = graphic;
	
			UIView * imageBackground  = [[UIView alloc] init];
			CGRect adjFrame           = showImage.frame;
			adjFrame.origin.x--;
			adjFrame.origin.y--;
			adjFrame.size.height+=2;
			adjFrame.size.width+=2;
			imageBackground.backgroundColor = [UIColor grayColor];
			imageBackground.frame     = adjFrame;
			[cell addSubview:imageBackground];
			[imageBackground release];
	
			// Fonts for Labels
			UIFont* teeny_font        = [UIFont systemFontOfSize:14];
			UIFont* bold_large_font   = [UIFont boldSystemFontOfSize:18];
	
			// Allocate labels
			UILabel *nameLabel        = [[UILabel alloc] initWithFrame:CGRectMake(60.0, 7.0, 200.0, 20.0)];
			UILabel *jobLabel         = [[UILabel alloc] initWithFrame:CGRectMake(60.0, 27.0, 200.0, 20.0)];
	
			// Build Name Label
			nameLabel.text			  = [@"" stringByAppendingFormat:@"%@ %@", relationship.target.givenName, relationship.target.familyName];
			nameLabel.font            = bold_large_font;
	
			nameLabel.backgroundColor = [UIColor clearColor];
			jobLabel.backgroundColor  = [UIColor clearColor];
	
			// Set text color
			nameLabel.textColor       = textColor;
			jobLabel.textColor        = textColor;
			cell.textColor            = textColor;
	
			// Set label in cell
			[cell addSubview:nameLabel];
	
			// Do we have a company?
			if (relationship.target.hometown) {
				// Build company label
				jobLabel.text		  = relationship.target.hometown;
				jobLabel.font         = teeny_font;
		
				// Set label in cell
				[cell addSubview:jobLabel];
				}
	
			// Add image to cell
			[cell addSubview:showImage];
	
			// Cleanup our junk
			[showImage release];
			[graphic release];
			[nameLabel release];
			[jobLabel release];
	
			return cell;
		}
	
	return cell;
}	

-(void)reloadData {
	[self loadFilter];
	[self.myRelationshipsTable reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	NSString * offset = [self.filter objectAtIndex:indexPath.row];
	
	NSIndexPath * myPath = [NSIndexPath indexPathForRow:[offset intValue] inSection:indexPath.section];	
	UITableViewCell *hitCell = [tableView cellForRowAtIndexPath:myPath];	
    [hitCell setSelected:NO animated:YES];
	
	UIBarButtonItem *backBar = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleDone target:nil action:nil];
	self.navigationItem.backBarButtonItem = backBar;	
	[backBar release];
		
	switch (indexPath.section) {
		case 0:
			[myApp slideRelationshipsPendingRelationshipsIn];
			break;
		case 1:
			[self showHoverView:YES];
			// Reset status, in the event there is NO status
			myApp.relationshipStatus.status    = nil;
			myApp.relationshipStatus.timeStamp = nil;
			Relationship *relationship = (Relationship*)[myApp.relationships objectAtIndex:[offset intValue]]; 
			[myApp.cliqset getRelationshipStatus:relationship.targetIdentifier];
			[myApp.cliqset loadRelationshipEvents:relationship.targetIdentifier offset:[offset intValue]];
			break;
		}
}

#pragma mark ---- Final memory cleanup ----	
- (void)dealloc {
	[filter release];
	[HoverView release];
	[navBarImage release];
	[myRelationshipsTable release];
	[mySegControl release];
	[myNavBar release];
    [super dealloc];
}

@end
